<template>
	<view class="form-container">
		<view class="form-card">
			<u--form labelPosition="left" :model="form" :rules="rules" ref="dataForm" labelWidth="160rpx">
				<!-- 表单项目 -->
				<u-form-item label="标题" prop="title" borderBottom>
					<u--input v-model="form.title" border="none" placeholder="请输入标题" class="custom-input"></u--input>
				</u-form-item>

				<u-form-item label="内容" prop="content" borderBottom>
					<u--textarea v-model="form.content" border="bottom" height="240rpx" placeholder="请输入详细内容..."
						class="custom-textarea"></u--textarea>
				</u-form-item>

				<u-form-item label="上传图片" prop="img" borderBottom>
					<view class="upload-container">
						<u-upload :fileList="form.img" @afterRead="onChooseAvatar" @delete="handleDelete"
							name="unlimitedUpload" multiple :maxCount="9" accept="image" :previewFullImage="true">
							<template #default>
								<view class="upload-btn">
									<u-icon name="plus" size="40" color="#4A90E2"></u-icon>
									<text class="upload-text">添加图片</text>
								</view>
							</template>
						</u-upload>
					</view>
				</u-form-item>
			</u--form>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-section">
			<u-button type="primary" text="提交需求" @click="submitForm" shape="circle" size="large" :loading="loading" />
			<text class="tip-text">提交后我们将在24小时内为您处理</text>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		toRefs
	} from "vue";
	import {
		postSave
	} from "../../../api/userInfo";
	import {
		showToast,
		showLoading,
		hideLoading
	} from "@/utils/toast";
	const state = reactive({
		form: {
			title: "",
			content: "",
			img: [],
		},
		rules: {
			title: [{
				required: true,
				message: "请输入标题",
				trigger: "blur"
			}],
			content: [{
				required: true,
				message: "请输入内容",
				trigger: "blur"
			}],
		},
	});
	const dataForm = ref(null); // 表单引用
	const {
		form,
		rules
	} = toRefs(state);
	// 提交表单

	const handleDelete = (event) => {
		form.value.img.splice(event.index, 1);
	};

	const onChooseAvatar = async (e) => {
		try {
			const newFiles = e.file;
			const listUrl = await uploadFilePromise(newFiles[0].url);
			console.log(listUrl);

			form.value.img = [
				...form.value.img,
				{
					url: listUrl.web_url,
					web_url: listUrl.url,
				},
			];
		} catch (err) {
			showToast("获取图片失败，请重试");
		}
	};
	// 上传文件到服务器
	const uploadFilePromise = (filePath) => {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: `${import.meta.env.VITE_API_URL}/upload/image`,
				filePath: filePath,
				name: "file",
				header: {
					Authorization: "Bearer " + uni.getStorageSync("token"),
					"content-type": "multipart/form-data; charset=utf-8",
				},
				formData: {
					file_type: "5",
					type: "avatar",
				},
				success: (res) => {
					const data = JSON.parse(res.data);
					if (data.code == 10000 && data.data?.url) {
						resolve(data.data);
					} else {
						reject(new Error(data.msg || "上传失败"));
					}
				},
				fail: (err) => {
					reject(err);
				},
			});
		});
	};
	const submitForm = async () => {
		dataForm.value
			.validate()
			.then(async (valid) => {
				if (valid) {
					console.log("表单验证通过:", form.value);

					try {
						showLoading("提交中...");
						const res = await postSave(form.value);
						hideLoading();
						if (res.code == 10000) {
							showToast("提交成功");
							setTimeout(() => {
								uni.navigateBack({
									delta: 1, // 延时1秒后返回上一页
								});
							}, 1000); // 1000毫秒 = 1秒
						} else {
							showToast(res.message || "提交失败，请重试");
						}
					} catch (error) {
						hideLoading();
						showToast("网络错误，请重试");
						console.error("提交错误:", error);
					}
				} else {
					showToast("请检查表单是否填写完整");
				}
			})
			.catch(() => {
				showToast("请检查表单是否填写完整");
			});
	};
</script>

<style lang="scss" scoped>
	.submit-section {
		margin-top: 60rpx;
		text-align: center;

		.tip-text {
			display: block;
			color: #999;
			font-size: 24rpx;
			margin-top: 20rpx;
		}
	}

	.form-container {
		padding: 30rpx;
		background-color: #f7f8fa;
		min-height: 100vh;
		box-sizing: border-box;
	}

	.form-card {
		background: #ffffff;
		border-radius: 20rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
	}

	.custom-input {
		font-size: 30rpx;
		color: #333;
		padding: 20rpx 0;
	}

	.custom-textarea {
		font-size: 28rpx;
		color: #333;
		// padding: 20rpx 0;
	}

	.upload-container {
		padding: 20rpx 0;
	}

	.upload-btn {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 160rpx;
		height: 160rpx;
		background: #f7f8fa;
		border-radius: 12rpx;
		border: 2rpx dashed #dcdfe6;
	}

	.upload-text {
		font-size: 24rpx;
		color: #909399;
		margin-top: 10rpx;
	}

	.delete-icon {
		position: absolute;
		top: 6rpx;
		right: 6rpx;
		z-index: 2;
		background: rgba(255, 255, 255, 0.7);
		border-radius: 50%;
	}

	.submit-section {
		margin-top: 60rpx;
		text-align: center;

		.tip-text {
			display: block;
			color: #999;
			font-size: 24rpx;
			margin-top: 20rpx;
		}
	}
</style>